package cn.iocoder.yudao.module.cmt.service.content;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.content.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.content.ContentArticleCategoryDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.content.ContentArticleCategoryMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class ContentArticleCategoryServiceImpl implements ContentArticleCategoryService {

    @Resource
    private ContentArticleCategoryMapper contentArticleCategoryMapper;

    @Override
    public Long createArticleCategory(ContentArticleCategorySaveReqVO createReqVO) {
        ContentArticleCategoryDO articleCategory = BeanUtils.toBean(createReqVO, ContentArticleCategoryDO.class);
        contentArticleCategoryMapper.insert(articleCategory);
        return articleCategory.getId();
    }

    @Override
    public void updateArticleCategory(ContentArticleCategorySaveReqVO updateReqVO) {
        validateArticleCategoryExists(updateReqVO.getId());
        ContentArticleCategoryDO updateObj = BeanUtils.toBean(updateReqVO, ContentArticleCategoryDO.class);
        contentArticleCategoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteArticleCategory(Long id) {
        validateArticleCategoryExists(id);
        contentArticleCategoryMapper.deleteById(id);
    }

    private void validateArticleCategoryExists(Long id) {
        if (contentArticleCategoryMapper.selectById(id) == null) {
            throw exception(ARTICLE_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public ContentArticleCategoryDO getArticleCategory(Long id) {
        return contentArticleCategoryMapper.selectById(id);
    }

    @Override
    public PageResult<ContentArticleCategoryDO> getArticleCategoryPage(ContentArticleCategoryPageReqVO pageReqVO) {
        return contentArticleCategoryMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteArticleCategoryListByIds(List<Long> ids) {
        ids.forEach(this::validateArticleCategoryExists);
        contentArticleCategoryMapper.deleteBatchIds(ids);
    }

}
